package com.Lyoto.NetNotify.Handler.impl;

import com.Lyoto.NetNotify.Handler.NetHandler;
import com.Lyoto.NetNotify.NetChecks.Checker;
import com.Lyoto.NetNotify.NetChecks.impl.NetStatusChecker;
import com.Lyoto.NetNotify.Notifier.Notify;
import com.Lyoto.NetNotify.Notifier.impl.NetworkNotify;
import com.Lyoto.NetNotify.Schedule.TimerSchedule;
import lombok.extern.slf4j.Slf4j;

import java.util.Timer;

/**
 * @author Lyoto
 * @Description
 * @Date 2022-09-19 15:14
 * @Version
 **/
@Slf4j
public class DefaultNetHandler implements NetHandler {
    private static volatile DefaultNetHandler handler;
    TimerSchedule<Timer> timerSchedule;

    @Override
    public void spin(TimerSchedule<Timer> timerSchedule) {
        timerSchedule.exec(this::doHandler);
        try {
            Thread.currentThread().join();
        } catch (InterruptedException e) {
            log.error("IP处理|设置任务出现错误:",e);
            log.error("IP处理|重新设置任务");
            spin();
        }
    }
    private DefaultNetHandler(){}

    public static DefaultNetHandler singleton(){
        if (handler == null){
            synchronized (DefaultNetHandler.class){
                if (handler == null){
                    handler = new DefaultNetHandler();
                }
            }
        }
        return handler;
    }
    
    @Override
    public void doHandler() {
        Notify notify = createNotify(createChecker());
        notify.notifyChangeIp();
    }

    @Override
    public void exec() {

    }

    protected Checker createChecker() {
        return NetStatusChecker.singletonInstance();
    }
    
    protected Notify createNotify(Checker checker) {
        return NetworkNotify.singletonInstance(checker);
    }
    
}
